<?php
namespace App\Services;

use App\Services\Openssl\OrderDistributeException;
use App\Services\Array2XML;
use Config, Log;

/**
* 订单派发服务
*/
class OrderDistribute
{

    protected $config;            //配置文件
    protected $ecpCode;            //电商平台代码
    protected $pallet_zone;        //仓库编码
    protected $owner_no;           //货主
    protected $po_no;              //提单号，集货提单号

    public function __construct()
    {

        $config = config('eorderinfo');

        $this->ecpCode = $config['ecpCodeCus_new'];//电商平台代码
        $this->ecpName = $config['ecpNameCus'];//电商平台名称

        //$this->shipper = $config['shipper'];
        $this->shipper = '河南中原福塔电子商务有限公司';
        $this->shipperAddress = $config['shipperAddress'];
        $this->shipperTelephone = $config['shipperTelephone'];

        $this->ecpCodeCus_new = $config['ecpCodeCus_new'];
        $this->companyName = $config['companyName'];
        $this->phone = $config['phone'];
        $this->address = $config['address'];


        $this->pallet_zone = $config['pallet_zone'];
        $this->owner_no = $config['owner_no'];
        $this->po_no = $config['po_no'];

        $this->config = $config;

    }


    public function distribute($order){

        $batchNumbers = strtotime($order->shipping_time);

        // $batchNumbers = strtotime($order->add_time);
        $batchNumbers = date('Ymd',$batchNumbers);
        /*$nowHour = date('H',$batchNumbers);
        if($nowHour>=0 && $nowHour<12){
                $batchNumbers .= '1';
        }elseif($nowHour>=12 && $nowHour<24){
                $batchNumbers .= '2';
        }//end if()*/

        $shipper_no = '';

        switch ($order->shipping_type) {

            case 'eto':
                $shipper_no = 'L0003';          //申通快递
                break;

            case 'yto':
                $shipper_no = 'L0007';          //圆通快递
                break;
        }

        $xmlOrder['orderHead'] = [

            /*'ORDER_SOURCE' => $this->ecpCode,//  必填，电商代码
            'SOURCEEXP_NO' => $order->order_sn,//  必填，订单编号*/

            'palletzone' => $this->pallet_zone,//  必填，仓库编码
            'owner_no' => $this->owner_no,//  必填，货主
            'sourceexp_no' => $order->order_sn,//  必填，订单号
            'exp_type' => 'B2C',//  必填，订单类型，B2C-电商,B2B-批发，B2B-门店
            'po_no' => ' ',//  必填，提单号，集货提单号
            'jh_type' => '2',//  必填，贸易类型，0-集货进口；1-集货出口，2-备货，3-直邮，4-一般贸易
            'exp_remark' => ' ',//  必填，出货备注
            'shipper_no' => $shipper_no,//  必填，承运商，"承运商：L0001 邮政速递，L0002 顺丰，L0003 申通，L0004 中通，L0005 中启，L0006 中大门，L0007  圆通，L0008 优速，L0009 宅急送，L0010 韵达，L0011 嘉里大通，L0012 百世，L0013 燕文，L0014 安达，L0015 全峰，L0016 晟邦，L0017 天天，L0018 邮政"
            'shipper_deliver_no' => $order->shipping_num,//  必填，运单号
            'order_source' => $this->ecpCode,//  必填，电商平台，电商代码
            'rsv_varod3' => '0',//  必填，布控标识，字符预留字段,【保税布控状态；0：不布控；1：布控】
            'send_address' => $this->config['address'],//  必填，发货人地址
            'send_name' => $this->config['companyName'],//  必填，发货人
            'send_company_name' => $this->config['companyName'],//  非必填，发货人公司名称
            'send_postcode' => $this->config['send_postcode'],//  非必填，发货人邮编
            'send_mobile_phone' => $this->config['phone'],//  必填，发货人手机
            'send_telephone' => $this->config['phone'],//  非必填，发货人固定电话
            'send_province' => $this->config['send_province'],//  必填，发货省份
            'send_city' => $this->config['send_city'],//  必填，发货市
            'send_zone' => $this->config['send_zone'],//  必填，发货区
            'send_country' => $this->config['send_country'],//  必填，发货村镇
            'cust_address' => $order->address,//  必填，收货人地址
            'contactor_name' => $order->consignee,//  必填，收货人
            'cust_phone' => $order->mobile,//  必填，收货人电话
            'cust_mail' => ' ',//  必填，收货人邮箱
            'receive_province' => $order->province,//  必填，收货省份
            'receive_city' => $order->city,//  必填，收货市
            'receive_zone' => $order->district,//  必填，收货区
            'receive_country' => ' ',//  必填，收货村镇
            'status' => '1',//  必填，状态，1:正常；0：撤销
            'zt_flag' => '0',//  非必填，自提标识，1：自提；0；普通
            'order_batch' => 'ZYFT'.$batchNumbers,//  必填，订单批次号，

            ];

        foreach ($order->orderGoods as $k => $goods) {

            $xmlOrder['orderList'][$k] = [

                /*'barcode' => $goods->goods_bar_code,//  必填，商品条形码
                'ARTICLE_NO' => $goods->goods_sn,//  必填，商品编号
                'ARTICLE_IDENTIFIER' => $goods->item_record_no,//  必填，商品备案号
                'ARTICLE_QTY' => $goods->buy_number,//  必填，数量
                'ITEM_TYPE' => '0',//  必填，是否赠品*/
                'sourceexp_no' => $order->order_sn,//  必填，订单号
                'article_no' => $goods->goods_sn,//  必填，商品编码(唯一ID)
                'barcode' => $goods->goods_bar_code,//  必填，商品条码
                // 'article_identifier' => $goods->item_record_no,//  必填，商品备案号
                'article_identifier' => $goods->goods_sn,//  必填，商品备案号
                // 'packing_qty' => $goods->packageTypeCus,//  必填，包装规格
                'packing_qty' => '1',//  必填，包装规格
                'article_qty' => $goods->buy_number,//  必填，计划数量
                'unit_cost' => $goods->goods_real_price,//  必填，单价
                'item_type' => '0',//  必填，商品类型，订单商品类型：0-普通；1-赠品

                ];
        }

        $xml = Array2XML::createXML('order', $xmlOrder)->saveXML();
        // echo $xml;exit();

        // echo $xmlorder;
        // return $this->makeRequest($this->config['orderDistribute'], ['xml' => $xml]);
        return $this->makeRequest($this->config['orderDistribute'], $xml);
    }


    /**
     * 构建请求
     * @param $data
     * @return mixed|string
     */
    private function makeRequest($url, $data)
    {

        try {
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
            curl_setopt($ch, CURLOPT_HEADER, 0);
            // curl_setopt($ch, CURLOPT_HTTPHEADER, Array("Content-Type:application/xml; charset=utf-8"));
            // curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']); // 模拟用户使用的浏览器
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            // curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
            curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
            $response = curl_exec($ch);

        }catch (\Exception $e){

            throw new OrderDistributeException($e->getMessage());
        }

        return $response;

    }


}

?>